<template>
  <div class="login"   @keyup.enter="enterEvent">
      <!-- 退出 -->
    <div class="exit" @click="closeLogin">
        <span class="iconfont icon-cha"></span>
    </div>
    <!-- 图片 -->
    <div class="img-wrapper">
        <!-- <img :src="pwdInputIsFocus ? imgSrc[1] : imgSrc[0]" > -->
        <img v-if="pwdInputIsFocus" src="../assets/img/login/login-2.png" alt="">
        <img v-if="!pwdInputIsFocus" src="../assets/img/login/login-1.png" alt="">
    </div>
    <!-- 表单 -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="60px"
      class="ruleForm"
    >
      <el-form-item label="账号" prop="count">
        <el-input v-model="ruleForm.count" maxlength="6"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input v-model="ruleForm.pwd" @focus="getFocus" @blur="loseFocus" type="password" maxlength="12"></el-input>
      </el-form-item>
      <el-form-item v-if="isLogin" class="login-btn-box">
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="register">注册</el-button>
      </el-form-item>
      <el-form-item v-else class="register-btn-box">
        <el-button type="primary" @click="submitForm('ruleForm')">确认注册</el-button>
      </el-form-item>
    </el-form>
    <!-- 协议 -->
    <p class="agreement">注册登录即表示同意
        <router-link to="/userAgree"> 用户协议</router-link>、
        <router-link to="/privacyPolicy">隐私政策</router-link>
    </p>
  </div>
</template>

<script>
export default {
    data() {
        return {
            ruleForm: {
                count: "", // 账号
                pwd: ""  // 密码
            },
            rules: { // 验证规则
                count: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 6, message: '长度为 6 个字符', trigger: 'blur' }
                ],
                pwd: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度为 6 - 12 个字符', trigger: 'blur' }
                ]
            },
            imgSrc: ["src/assets/img/login/login-1.png", "../assets/img/login/login-2.png"], // 图片地址
            pwdInputIsFocus: false, // 密码框是否获得焦点
            isLogin: true // 当前组件是否为登录状态
            
        }
    },
    methods: {
        
        // 密码框获得焦点
        getFocus() {
            this.pwdInputIsFocus = true
        },
        // 密码框失去焦点
        loseFocus() {
            this.pwdInputIsFocus = false
        },
        // 登录
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 判断当前表单是登录表单还是注册表单
                    if (this.isLogin) {
                        // 登录
                        this.axios.post(
                            "http://api_devss.wanxikeji.cn/api/login",
                            {name: this.ruleForm.count, pw: this.ruleForm.pwd}
                        ).then( res => {
                            console.log(res)
                            if (res.status === 200) {
                                // 跳转
                                document.cookie = `token = ${res.data.data.token};expires = ${(new Date(new Date().getTime() + 3*24*3600*1000)).toUTCString()}`
                                document.cookie = `icon = ${res.data.data.icon};expires = ${(new Date(new Date().getTime() + 3*24*3600*1000)).toUTCString()}`
                                document.cookie = `nickName = ${res.data.data.nick_name};expires = ${(new Date(new Date().getTime() + 3*24*3600*1000)).toUTCString()}`
                                document.cookie = `userID = ${res.data.data.user_id};expires = ${(new Date(new Date().getTime() + 3*24*3600*1000)).toUTCString()}`
                                this.$store.commit("splitCookie")
                                //重新获取用户数据
                                this.eventBus.$emit("xxx")
                                this.closeLogin()
                            } else {
                                this.$message({
                                    message: '账号密码错误',
                                    type: 'error',
                                    duration: 1500
                                })
                            }
                        }).catch( err => {
                            console.error(err)
                        })
                    } else {
                        // 注册
                        this.axios.post(
                            "http://api_devss.wanxikeji.cn/api/register",
                            {name: this.ruleForm.count, pw: this.ruleForm.pwd}
                        ).then(res => {
                            console.log(res)
                            if (res.status === 200) {
                                this.jumpToLogin()
                            } else {
                                this.$message({
                                    message: '账号不可用',
                                    type: 'error',
                                    duration: 1500
                                })
                            }
                        }).catch((err) => {
                            console.error(err)
                        })
                    }
                } else {
                    this.$message({
                    message: '请输入账号密码',
                    type: 'error',
                    duration: 1500
                    })
                    return false;
                }
            })
        },
        // 注册
        register() {
            this.isLogin = false
        },
        // 登录跳转
        jumpToLogin() {
            this.$message({
                message: '注册成功，即将跳转至登录页面',
                type: 'success',
                duration: 1500
            })
            // 跳转至登录
            setTimeout(()=>{
                this.isLogin = true
            }, 2000)
        },
        // 关闭登录组件
        closeLogin() {
            this.$emit("loginSwitch")
        },
        // enter
        enterEvent() {
            this.submitForm('ruleForm')
        }
    }
    
}
</script>

<style lang="scss" scoped>
.login {
    position: relative;
    width: 400px;
    padding: 20px;
    background-color: #fff;
}

.login .exit {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    color: #ccc;
    transition: all .3s;
    z-index: 99;
    cursor: pointer;
    
    span {
        font-size: 22px;
    }
}

.login .exit:hover {
    color: #000;
}

.login .img-wrapper {
    position: relative;
    top: 10px;
    display: flex;
    justify-content: center;
    width: 100%;
    height: 100px;
    z-index: 10;
}

.login .login-btn-box .el-form-item__content .el-button--default {
    margin-left: 200px;
}

.login .register-btn-box button {
    width: 100%;
}

.login .agreement {
    color: #767676;
    font-size: 14px;
}

.login .agreement a {
    color: #007fff;
}
</style>
